package com.qinhailin.portal.dbm.service;

import java.sql.Timestamp;

import com.jfinal.plugin.activerecord.Model;
import com.qinhailin.common.model.BaseMasterModel;
import com.qinhailin.common.util.DateUtil;

public class MasterServiceImpl<T extends BaseMasterModel<T>> extends BaseServiceImpl<T>{

	
	
	
	public MasterServiceImpl(T dao) {
		super(dao);
	}

	public T findByIDs(Object... ids) {
		return this.dao.findByIds(ids);
	}
	
	public T findByID(Integer sID) {
		return this.dao.findById(sID);
	}

	@Override
	public boolean save(Model<?> entity) {
		//if(entity.get)
		if(dao.primaryKeyType() != null && (entity.getInt("sID") == null || entity.getInt("sID").equals(0))) {
			// 由存储过程提供
			if(dao.primaryKeyType().equals(2)) {
				entity.set("sID", idService.cp_getid(0, dao.tableName(), 1));
			}
			// 程序控制自增
			else if(dao.primaryKeyType().equals(1)) {
				//this.find
				T r = (T) this.findBySql("SELECT TOP(1) * FROM " + dao.tableName() + " ORDER BY sID DESC");
				if(r != null && r.getInt("sID") != null) {
					entity.set("sID", r.getInt("sID") + 1);
				}else {
					entity.set("sID", 1);
				}
			}
			// 其他
			else {
				// 不做处理
			}
		}
		Timestamp now = DateUtil.getCurrentTimestamp();
		entity.set("sCreateTime", now).set("sLastUpdate", now).set("sVersion", 1);
		return super.save(entity);
	}

	@Override
	public boolean update(Model<?> entity) {
		T t = this.findByID(entity.getInt("sID"));
		entity.set("sVersion", t.getSVersion() + 1).set("sLastUpdate", DateUtil.getCurrentTimestamp());
		return super.update(entity);
	}
	
	
	
	

}
